package com.liqian.demo.controller;

import com.liqian.demo.dto.ResultDto;
import com.liqian.demo.service.FileSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件搜索控制器
 * @start 2017/9/1日
 * @last 2017/9/15日
 * @version 1.0
 * @author LiQian
 */
@Controller
@RequestMapping("file")
public class FileSearchController {

    @Autowired
    private FileSearchService fileSearchService;

    @ResponseBody
    @RequestMapping(value = "/createIndex.json", method = RequestMethod.GET)
    public Map<String, String> createIndex() {

        Map<String, String> result = new HashMap<>();

        try {
            fileSearchService.createIndex();
            result.put("code", "1");
            result.put("msg", "创建索引成功");
        } catch (Exception e) {
            result.put("code", "-1");
            result.put("msg", "创建索引失败");
        }

        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/search.json/{keyWord}", method = RequestMethod.GET)
    public Map<String, Object> search(@PathVariable("keyWord") String keyWord) {

        Map<String, Object> result = new HashMap<>();

        try {
            List<ResultDto> resultDtoList = fileSearchService.search(keyWord);
            result.put("code", "1");
            result.put("msg", "成功");
            result.put("data", resultDtoList);
        } catch (Exception e) {
            result.put("code", "-1");
            result.put("msg", "失败");
        }

        return result;
    }

    @RequestMapping(value = "/search/{keyWord}", method = RequestMethod.GET)
    public ModelAndView result(@PathVariable("keyWord") String keyWord) {

        ModelAndView mav = new ModelAndView("list");

        try {
            List<ResultDto> resultDtoList = fileSearchService.search(keyWord);
            mav.addObject("data", resultDtoList);
        } finally {

        }
        return mav;
    }
}
